using System;
using System.ComponentModel;

namespace Clancy.Data
{
    public class PercentageTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return (sourceType == typeof(string));
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return (destinationType == typeof(string));
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string val = value as string;
            if (val == null)
                return 0;

            val = val.Trim().Trim('%');
            return (double.Parse(val) / 100.0f);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            double val = (double)value;
            return string.Format("{0}%", val * 100);
        }
    }
}